package org.jsola.hr.task;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.jsola.hr.common.HrLogKit;
import org.jsola.hr.constant.ApprovalStatusEnum;
import org.jsola.hr.constant.PersonalEventEnum;
import org.jsola.hr.dao.IPersonalEventDAO;
import org.jsola.hr.dto.EmpInfoUpdateDTO;
import org.jsola.hr.entity.EmpInfoDO;
import org.jsola.hr.example.PersonalEventExample;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.service.IPersonalEventService;
import org.jsola.hr.vo.EmpInfoVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 自动转正,将转正日期是今天的员工自动转为正式员工
 *
 * @author zxy
 */
@Slf4j
@Component
public class TurnStraightTask {

    @Autowired
    private IEmpInfoService empInfoService;
    @Autowired
    private IPersonalEventService personalEventService;

    /**
     * 自动转正,将转正日期是今天的员工自动转为正式员工
     * 每天0点5分0秒触发
     */
    @XxlJob("auditTurnStraightTask")
    public ReturnT<String> auditTurnStraightTask(String param) {
        XxlJobLogger.log("=================自动转正开始");
        try {
            // 获取系统中需要转正的员工
            List<EmpInfoDO> empInfoList = empInfoService.listTurnStraightTaskToday();
            if (CollectionUtils.isEmpty(empInfoList)) {
                return ReturnT.SUCCESS;
            }
            for (EmpInfoDO empInfo : empInfoList) {
                EmpInfoUpdateDTO empInfoUp = empInfo.to(EmpInfoUpdateDTO.class);
                // 员工变动状态（0：当前无变动，1：转正中，2：调岗中，3： 离职中）
                empInfoUp.setChangeStatus(0);
                // 正式类型（1：试用期，2：已转正）
                empInfoUp.setFormalType(2);
                empInfoUp.setApprovalStatus(ApprovalStatusEnum.APPRO_DISABLE.getValue());

                // 根据员工构建当前用户
                TokenUser tokenUser = new TokenUser();
                tokenUser.setUserId("system");
                tokenUser.setSiteId(empInfo.getSiteId());

                empInfoService.update(empInfoUp, tokenUser);
                String desc = "试用期已满，自动转正";
                personalEventService.autoSave(empInfo.to(EmpInfoVO.class), tokenUser, desc
                        , PersonalEventEnum.REGULAR_WORKER.getValue(), PersonalEventEnum.REGULAR_WORKER.getDesc());

//                HrLogKit.logForSave("系统定时任务-员工转正,empName:" + empInfo.getName()
//                        , "auditTurnStraightTask", empInfo.getId(), tokenUser);
            }
        } catch (Exception e) {
            XxlJobLogger.log("=================自动转正失败，失败原因：{}", e.toString());
        }
        XxlJobLogger.log("=================自动转正完成");
        return ReturnT.SUCCESS;
    }


}
